<template>
  <div
    v-loading="isDingDing"
    element-loading-text="登录中..."
    class="page-login"
    :style="{ backgroundImage: `url(${bgImg})` }"
  >
    <div v-if="!isDingDing" class="card-wrap bgf">
      <div class="logo" :style="{ 'background-image': `url(${info.ico})` }"></div>

      <div class="login-title" @dblclick="setLoginInfo">
        <span
          v-for="(item, index) in info.systemName"
          :key="index"
          class="title-item"
          :style="systemNameStyle"
          >{{ item }}</span
        >
      </div>
      <el-form ref="loginForm" label-position="top" :rules="rules" :model="form" size="default">
        <el-form-item prop="userName">
          <el-input v-model="form.userName" type="text" placeholder="用户名">
            <i slot="prepend" class="el-icon-user-solid"></i>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            @keyup.enter.native="passwordKeyUp"
          >
            <i slot="prepend" class="el-icon-key"></i>
          </el-input>
        </el-form-item>

        <el-form-item v-if="showCodeFlag" prop="checkCode" class="check-code">
          <el-input v-model="form.code" placeholder="验证码" @keyup.enter.native="submit">
            <template slot="append">
              <div class="img-wrap fcc">
                <img
                  v-if="authCodeImgSrc"
                  class="login-code"
                  width="108"
                  height="34"
                  :src="authCodeImgSrc"
                  @click="_GetCaptcha"
                />
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-button
          size="default"
          type="primary"
          class="button-login"
          :loading="btnLoading"
          @click="submit"
        >
          {{ `登录${btnLoading ? "中..." : ""}` }}
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { encrypt } from "@/libs/rsaEncrypt";
import util from "@/libs/util";
import { GetCaptcha } from "api/sys";
import { LogoGet } from "api/sys-logo-config";
import { Loading } from "element-ui";
// import dd from "gdt-jsapi";
import { titleStyle } from "./config";
import rules from "./config/rules";
import IsImage from "is-image";

export default {
  name: "login",
  components: {},
  data() {
    return {
      // 表单
      form: {
        userName: "",
        password: "",
        code: "",
      },
      // 表单校验规则
      rules,
      // 提交按钮loading
      btnLoading: false,
      // 验证码图片
      authCodeImgSrc: "",
      // 标题字体大小配置文件
      titleStyle,
      uId:'',
    };
  },
  computed: {
    ...mapState("d2admin", {
      info: (state) => state.sysConfig.info,
      routerList: (state) => state.router.routerList,
    }),
    systemNameStyle() {
      const { systemName } = this.info;
      if (!(systemName && systemName.length)) return 0;
      return this.titleStyle[this.info.systemName.length];
    },
    // 是否显示验证码
    showCodeFlag() {
      return this.info.checkCodeFlag === "0";
    },
    isDingDing() {
      const userAgent = window.navigator.userAgent.toLowerCase();
      return userAgent.indexOf("dingtalk") !== -1;
    },
    //  背景图片
    bgImg() {
      const { loginBackImg } = this.info;
      if (this.isDingDing) return "";
      const defaultBg = require("@/assets/imgs/login-bg.png");
      return IsImage(loginBackImg) && loginBackImg ? loginBackImg : defaultBg;
    },
  },
  created() {
    this.doInit();
  },
  mounted() {
    this.flag = 0;
  },
  beforeRouteLeave(to, from, next) {
    if (this.loginSuccess) {
      this.btnLoading = false;
      this.loginSuccess = false;
      // 刷新验证码
      this._GetCaptcha();
    }
    next();
  },
  methods: {
    ...mapActions({
      login: "d2admin/account/login",
      setSysConfig: "d2admin/sysConfig/set",
      commonInit: "d2admin/common/commonInit",
    }),
    /**
     * 初始化
     */
    async doInit() {
      // 初始化缓存数据
      await this.commonInit();
      await this._LogoGet();
      this.uId =  Date.now() + Math.random().toString(36).substr(2, 9);
      const authorization = util.getAddrPro("Authorization");
      if (authorization) {
        // 系统token登陆
        this.sysTokenLogin(authorization);
      } else {
        this._GetCaptcha();
      }
    },
    /**
     * 获取验证码
     */
    async _GetCaptcha() {
      try {
        if (this.showCodeFlag) {
          const data = await GetCaptcha({
            uuid:this.uId
          });
          if (data) {
            this.authCodeImgSrc = window.URL.createObjectURL(data);
          }
        }
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 登录
     */
    submit() {
      // 防止重复提交
      if (this.btnLoading) return;
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true;
          try { 
            await this.login({ params: { ...this.form, type: "0",uuid:this.uId,password:encrypt(this.form.password) }, vm: this });
            this.loginSuccess = true;
            this.pageJump();
          } catch (e) {
            console.log(e);
            this.btnLoading = false;
            this._GetCaptcha();
          }
        } else {
          // 登录表单校验失败
          return false;
        }
      });
    },
    /**
     * 设置默认登录信息
     */
    setLoginInfo() {
      if (this.$env === "development") {
        Object.assign(this.form, {
          userName: "JonSnow",
          password: "123456",
        });
      }
    },
    /**
     * 详情
     */
    async _LogoGet() {
      try {
        const data = await LogoGet();
        this.setSysConfig(data);
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 密码框的回车事件
     */
    passwordKeyUp() {
      if (!this.showCodeFlag) {
        this.submit();
      }
    },

    /**
     * 系统token登陆
     */
    sysTokenLogin(authorization) {
      let loadingInstance = Loading.service({
        lock: true,
        text: "登录中....",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.login({
        params: { authorization, type: "4" },
        vm: this,
      })
        .then(() => {
          loadingInstance.close();
          this.pageJump();
        })
        .catch((e) => {
          console.log(e);
          // code登录失败 使用密码登录
          loadingInstance.close();
          this.isDingding = false;
          this._GetCaptcha();
        });
    },

    /**
     * 页面跳转
     */
    pageJump() {
      setTimeout(() => {
        const [{ redirect }] = this.routerList;
        let name = "index";
        let query = null;
        if (redirect) {
          name = redirect.name;
          query = redirect.query;
        }
        this.$router.push({ name, query });
        // 后续的逻辑在beforeRouteLeave中统一进行拦截
      }, 100);
    },
  },
};
</script>

<style lang="scss" scoped>
.page-login {
  $backgroundColor: #f0f2f5;
  background-color: $backgroundColor;
  height: 100vh;
  width: 100vw;
  position: relative;
  overflow: auto;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  @media screen and (max-width: 1000px) {
    .card-wrap {
      left: 0;
      right: 0;
    }
  }
  @media screen and (min-width: 1000px) {
    .card-wrap {
      right: 10%;
    }
  }
  // 卡片
  .card-wrap {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    height: fit-content;
    width: 350px;
    padding: 20px;
    padding-bottom: 24px;
    border-radius: 4px;
    .logo {
      height: 120px;
      width: 120px;
      border-radius: 50%;
      box-shadow: 0px 3px 8px 0px rgba(198, 215, 249, 0.26);
      position: absolute;
      top: -78px;
      left: 0;
      right: 0;
      margin: auto;
      background-repeat: no-repeat;
      border: 5px solid #fff;

      background-size: 100% 100%;
      z-index: 1;
    }
    .login-icon2 {
      height: 55px;
      width: 30px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: absolute;
      top: 0;
      left: 85%;
    }
    .login-title {
      height: 40px;
      margin-top: 30px;
      margin-bottom: 10px;
      text-align: center;
      font-weight: bold;
      color: #5794ff;
      user-select: none;
      display: flex;
      align-items: center;
      justify-content: center;
      .title-item {
        font-size: 30px;
        padding: 0 4px;
      }
    }
    // 登录按钮
    .button-login {
      width: 100%;
    }
  }
}
.check-code {
  ::v-deep .el-input-group__append {
    padding-left: 0 !important;
    padding-right: 0 !important;
    background: #fff;
    cursor: pointer;
  }
  .img-wrap {
    width: 110px;
    height: 34px;
    .login-code {
      border: none;
    }
  }
}
</style>
